package com.blockchain.controller;

import com.blockchain.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
public class EmailController {


    private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
    private final EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/sendEmail")
    public ResponseEntity<String> sendEmail(@RequestBody Map<String,String> requestData) {
        try {
            String email=requestData.get("email");
            //生成验证码
            String captcha=generateCaptcha();
            //存储验证码
            emailService.storeCaptcha(email,captcha);
            emailService.sendEmail(email);
            return ResponseEntity.ok().body("Email sent successfully");
        } catch (Exception e) {
            logger.error("Failed to send Email", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to send Email: " + e.getMessage());
        }
    }
    // 生成6位随机数字验证码
    private String generateCaptcha() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    @CrossOrigin(origins = "http://localhost:8080")
    @PostMapping("/verifyCaptcha")
    public ResponseEntity<String> verifyCaptcha(@RequestBody Map<String,String> requestData){
        String email=requestData.get("email");
        String userCaptcha=requestData.get("captcha");
        //从存储中获取正确的验证码
        String correctCaptcha= emailService.getCaptcha(email);
        System.out.println(correctCaptcha);
        if(correctCaptcha !=null && correctCaptcha.equals(userCaptcha)){
            return ResponseEntity.ok().body("{\"message\":\"验证码验证通过\"}");
        }else {
            return ResponseEntity.ok().body("{\"error\":\"验证码错误或已过期，请重新输入\"}");
        }

    }
}
